#include <arpa/inet.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <unistd.h>

int main() {
    int client_socket;
    struct sockaddr_in server_addr;
    char buffer[1024];
    char username[100];
    char server_address[100];
    char password[100];
    char port[100];
    char login[100];

    // 创建套接字
    client_socket = socket(AF_INET, SOCK_STREAM, 0);

    printf("请登录（格式：用户名:密码@网盘地址:端口）");
    fgets(login, sizeof(login), stdin);
    if (sscanf(login, "%[^:]:%[^@]@%[^:]:%s", username, password, server_address, port) == 4) {
        printf("Username: %s\n", username);
        printf("Password: %s\n", password);
        printf("Server Address: %s\n", server_address);
        printf("Port: %s\n", port);
    } else {
        printf("格式错误，无法正确提取信息\n");
    }

    // 设置服务器地址结构
    server_addr.sin_family = AF_INET;
    server_addr.sin_addr.s_addr = inet_addr(server_address);  // 替换为实际的服务器IP地址
    server_addr.sin_port = htons(atoi(port));                 // 服务器端口号

    // 连接到服务器
    if (connect(client_socket, (struct sockaddr*)&server_addr, sizeof(server_addr)) == -1) {
        printf("连接失败");
        return 1;
    }

    printf("连接到服务器成功！\n");
    // 发送用户名给服务器
    send(client_socket, username, strlen(username), 0);

    // 发送和接收数据
    while (1) {
        printf("请输入要发送给对方的消息：");
        fgets(buffer, sizeof(buffer), stdin);
        send(client_socket, buffer, strlen(buffer), 0);

        recv(client_socket, buffer, sizeof(buffer), 0);
        printf("对方: %s\n", buffer);
    }

    // 关闭套接字
    close(client_socket);
    return 0;
}